package com.zx.scp.service.impl;


import com.zx.map.utils.CommonResponseUtils;
import com.zx.map.utils.MyBeanUtils;
import com.zx.map.utils.SUConstants;
import com.zx.platform.utils.DateUtils;
import com.zx.platform.utils.HttpClientCommon;
import com.zx.platform.utils.RSAUtils;
import com.zx.scp.service.IIncomeService;
import com.zx.scp.service.IncomHandleService;
import com.zx.scp.service.model.*;
import com.zx.scp.utils.PropertyUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * Created by IntelliJ IDEA. User: Administrator Date: 15-6-7 Time: 上午1:12 To
 * change this template use File | Settings | File Templates.
 */
@Service
public class YinTongIncomeServiceImpl implements IIncomeService {
	/**
	 * log
	 */
	private static Logger log = Logger.getLogger(YinTongIncomeServiceImpl.class);

	@Autowired
	private IncomHandleService incomHandleService;


	/**
	 * 装换对象 	 *
	 *
	 * @param map
	 * @param orderPayCallBackModel
	 */
	private void transModel(Map map, OrderPayCallBackModel orderPayCallBackModel) {
		orderPayCallBackModel.setOrdId((String) map.get("no_order"));
		orderPayCallBackModel.setPaymentAmt(Double.valueOf((String) map.get("money_order")));
		orderPayCallBackModel.setPaymentId((String) map.get("oid_order"));
		orderPayCallBackModel.setPaymentTime((String) map.get("settle_date"));
		String result = (String) map.get("result_pay");
		orderPayCallBackModel.setTransStatus("SUCCESS".equals(result) ? "S" : result);
	}


	/**
	 * 按照key的字母顺序排序后的,返回的字符串
	 *
	 * @param paramMap
	 * @throws UnsupportedEncodingException
	 */
	private String getSignatureString(Map<String, String> paramMap) {
		StringBuffer param = new StringBuffer("");
		List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(
				paramMap.entrySet());
		Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
			public int compare(Map.Entry<String, String> o1,
			                   Map.Entry<String, String> o2) {
				return (o1.getKey()).toString().compareTo(o2.getKey());
			}
		});
		for (int i = 0; i < infoIds.size(); i++) {
			Map.Entry<String, String> tmpMap = infoIds.get(i);
			if (!("sign".equalsIgnoreCase(tmpMap.getKey()) || "class"
					.equalsIgnoreCase(tmpMap.getKey()) || StringUtils.isBlank(tmpMap.getValue()))) {//增加值为空的判断
				param.append(tmpMap.getKey()).append("=")
						.append(tmpMap.getValue());
				if (i < infoIds.size() - 1) {// 拼接param参数
					param.append("&");
				}
			}
		}
		return param.toString();
	}


	@Override
	public Map startPay(HttpServletRequest request, YintongPayRequestModel orderResponseDomain) throws Exception {
		log.info("支付请求参数:" + MyBeanUtils.beanToJson(orderResponseDomain));
		Map<String, String> paramMap = new HashMap<String, String>();

		paramMap.put("dt_order", DateUtils.dateToString(new Date(), DateUtils.DATE_TIME_FMT_OTHER));
		paramMap.put("money_order", orderResponseDomain.getAmount());// 订单金额
		paramMap.put("no_order", orderResponseDomain.getOrderId());
		paramMap.put("notify_url", PropertyUtil.getValue("yt_notify_url"));
		paramMap.put("oid_partner", PropertyUtil.getValue("yt_mer_id"));
		if (orderResponseDomain.getPayType().equals(SUConstants.paymentTypeAlipay)) {
			paramMap.put("pay_type", "5");
		} else {
			paramMap.put("pay_type", "0");
		}
		paramMap.put("sign_type", "RSA");   // 请求签名方式RSA|MD5 RSA|MD5 RSA|MD5
		paramMap.put("risk_item", "pass");

		String signString = getSignatureString(paramMap);
		String sign = RSAUtils.sign(signString.getBytes(), PropertyUtil.getValue("yt_pri_key"));
		paramMap.put("sign", URLEncoder.encode(sign, "UTF-8")); //增加encode
		String requestUrl = PropertyUtil.getValue("yt_pay_url");
		// 2.请求
		String jsonParam = MyBeanUtils.beanToJson(paramMap);
		log.info("支付请求接口方url信息：" + requestUrl + " 参数信息：" + paramMap);
		HttpClientCommon httpClientCommon = new HttpClientCommon();
		Map response = httpClientCommon.getResult(Map.class, requestUrl, jsonParam);
		log.info("支付接口方返回信息:" + MyBeanUtils.beanToJson(response));

		String ret_code = (String) response.get("ret_code");
		Map orderResult = new HashMap();
		if ("000000".equals(ret_code)) {
			orderResult.put("codeUrl", response.get("dimension_url"));
			//orderResult.put("codeImgUrl", response.get("code_img_url"));  //zxing 编码
			return CommonResponseUtils.successResponse(orderResult);
		} else {
			return CommonResponseUtils.failureResponse();
		}

	}

	@Override
	public Map winxinJsPay(HttpServletRequest request, YintongPayRequestModel orderResponseDomain) throws Exception {
		return startPay(request, orderResponseDomain);
	}

	@Override
	public Map payNotify(Map paramMap) throws Exception {
		String signString = getSignatureString(paramMap);
		log.info("签名串：" + signString);
		boolean verifyFlag = RSAUtils.verify(signString.getBytes("UTF-8"), PropertyUtil.getValue("yt_pub_key"), (String) paramMap.get("sign"));
		Map map = new HashMap();
		if (verifyFlag) {
			log.debug("订单验签通过");
			OrderPayCallBackModel orderPayCallBackModel = new OrderPayCallBackModel();
			transModel(paramMap, orderPayCallBackModel);
			incomHandleService.handleOrderCallBack(orderPayCallBackModel);
			map.put("ret_code", "0000");//处理成功
			map.put("ret_msg", "处理成功");
		} else {
			log.error("验签失败");
			map.put("ret_code", "9000");//处理成功
			map.put("ret_msg", "验签失败");
		}
		return map;
	}
}
